package com.ccg.securityConfig;

import org.springframework.security.core.AuthenticationException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//验证码验证过滤器,继承OncePerRequestFilter,该过滤器作用于账户密码过滤器前
public class CheckCodeAuthenticationFilter extends OncePerRequestFilter {

    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    //用于在spring-security.xml将该过滤器注册到容器时,注入属性调用
    public void setMyAuthenticationFailureHandler(MyAuthenticationFailureHandler myAuthenticationFailureHandler) {
        this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //判断当前请求是否是登陆请求
        if (request.getRequestURI().contains("/securityLogin")) {
            //检验验证码
            try {
                //用户输入的验证码
                final String imageCode = request.getParameter("code");
                //获取系统生成的验证码
                String key = (String) request.getSession().getAttribute("checkCode");

                if (!imageCode.trim().equalsIgnoreCase(key.trim())) {
                    //抛出自定义验证码异常
                    throw new CheckCodeException("验证码不一致");
                }
            } catch (AuthenticationException e) {
                //交给authenticationFailureHandler（自定义登陆失败处理器)处理
                myAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }

        }
        //验证码正确放行
        filterChain.doFilter(request, response);
    }
}
